package org.jeecg.modules.demo.crm.aspect;


import java.lang.reflect.Field;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.JoinPoint;
import org.jeecg.modules.demo.crm.annotation.FileField;
import org.jeecg.modules.demo.crm.annotation.TitleField;
import org.jeecg.modules.demo.crm.entity.CFileRecord;
import org.jeecg.modules.demo.crm.mapper.CFileRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DataInterceptorAspect {

    @Autowired
    private CFileRecordMapper fileRecordMapper;

    // 定义切入点，拦截YourService中的saveYourEntity方法
    @Pointcut("execution(* com.baomidou.mybatisplus.core.mapper.BaseMapper.insert(..)) || " +
            "execution(* com.baomidou.mybatisplus.core.mapper.BaseMapper.updateById(..))")
    public void saveYourEntityPointcut() {

    }

    // 在方法执行后进行操作
    @AfterReturning(pointcut = "saveYourEntityPointcut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
            Object entity = args[0];
            // 遍历实体类的字段
            for (Field field : entity.getClass().getDeclaredFields()) {
                // 检查字段是否有@FileField注解
                if (field.isAnnotationPresent(FileField.class)) {
                    field.setAccessible(true); // 设置私有字段可访问
                    try {
                        Object fieldValue = field.get(entity);
                        if (fieldValue instanceof String && !((String) fieldValue).isEmpty()
                        ) {
                            String fileUrl = fieldValue.toString();
                            String entityTitle = getEntityTitle(entity, fieldValue);
                            String[] fileSplit = fileUrl.split(",");
                            for (String url : fileSplit) {
                                String entityId = getEntityId(entity,"id");
                                String projectId = getEntityId(entity,"projectId");
                                String subProjectId = getEntityId(entity,"subProjectId");
                                String fileType = getFileExtension(url);
                                // 如果字段值是文件地址，插入到file_table
                                CFileRecord fileEntity = new CFileRecord();
                                fileEntity.setRelatedId(entityId);
                                fileEntity.setProjectId(projectId);
                                fileEntity.setSubProjectId(subProjectId);
                                fileEntity.setFileUrl(url);
                                fileEntity.setFileName(entityTitle);
                                fileEntity.setFileType(fileType);
                                fileRecordMapper.insert(fileEntity);
                            }


                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // 通过反射获取实体类的id字段值
    private String getEntityId(Object entity,String name) {
        try {
            Field idField = entity.getClass().getDeclaredField(name); // 假设所有实体类都有一个名为id的字段
            idField.setAccessible(true); // 设置私有字段可访问
            return (String) idField.get(entity);
        } catch (NoSuchFieldException | IllegalAccessException e) {
           // e.printStackTrace();
            return null;
        }
    }

    private String getEntityTitle(Object entity,Object fieldValue){
        for (Field field : entity.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(TitleField.class)) {
                field.setAccessible(true); // 设置私有字段可访问
                try {
                    Object fieldTitleValue = field.get(entity);
                    if (fieldTitleValue instanceof String && !((String) fieldTitleValue).isEmpty()) {
                        return (String) fieldTitleValue;
                    }
                } catch (Exception e) {
                    //throw new RuntimeException(e);
                }
            }
        }
        if (fieldValue instanceof String && !((String) fieldValue).isEmpty()) {
            String fileName = getFileName(fieldValue.toString());
            return fileName;
        }
        return null;
    }

    public static String getFileName(String url) {
        // 从URL中提取文件名
        int lastSlashIndex = url.lastIndexOf('/');
        if (lastSlashIndex != -1 && lastSlashIndex < url.length() - 1) {
            return url.substring(lastSlashIndex + 1);
        }
        return "";
    }

    public static String getFileExtension(String url) {
        if(url != null ){
            // 从文件名中提取扩展名
            int lastDotIndex = url.lastIndexOf('.');
            if (lastDotIndex != -1 && lastDotIndex < url.length() - 1) {
                return url.substring(lastDotIndex + 1);
            }
            return "";
        }
        return null;
    }
}